<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>Hello MUI</title>
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">
		<link rel="stylesheet" href="../css/mui.css">
		<link rel="stylesheet" href="../css/style.css">
		<style>
			html,
			body {
				background-color: #efeff4;
			}
		</style>
	</head>

	<body>
		<div id="pullrefresh" class="mui-content mui-scroll-wrapper">
			<div class="mui-scroll">
				<div class="no-task">
					<p class="no-task-p">当日未有派单任务。</p>
				</div>
				<!--<div class="mui-card">
					<div class="mui-card-header mui-card-media">
						<img src="../images/car.png"/>
						<div class="mui-media-body">
							接人
							<p>2018-5-6 13:10:50</p>
						</div>
					</div>
					<div class="mui-card-content" >
						<div class="mui-row">
					        <div class="mui-col-sm-6 mui-col-xs-6">
					        	<div class="info-detail">							        		
					        		<div class="red-point"></div>
					        		<p class="info-key">联系人:</p>	
					        		<div class="info-value">阿灿笑眯眯的</div>
					        	</div>
					        </div>
					        <div class="mui-col-sm-6 mui-col-xs-6">
					        	<div class="info-detail">							        		
					        		<div class="orange-point"></div>
					        		<p class="info-key">电话:</p>	
					        		<div class="info-value">15366602513</div>
					        	</div>
					        </div>
					    </div>
					    
					    <div class="mui-row">
					        <div class="mui-col-sm-6 mui-col-xs-6">
					        	<div class="info-detail">							        		
					        		<div class="yellow-point"></div>
					        		<p class="info-key">始发地:</p>	
					        		<div class="info-value">南京站</div>
					        	</div>
					        </div>
					        <div class="mui-col-sm-6 mui-col-xs-6">
					        	<div class="info-detail">							        		
					        		<div class="green-point"></div>
					        		<p class="info-key">目的地:</p>	
					        		<div class="info-value">南京南</div>
					        	</div>
					        </div>
					    </div>
					    
					    <div class="mui-row">
					        <div class="mui-col-sm-6 mui-col-xs-6">
					        	<div class="info-detail">							        		
					        		<div class="cyan-point"></div>
					        		<p class="info-key">开始时间:</p>	
					        		<div class="info-value">8:15:12</div>
					        	</div>
					        </div>
					        <div class="mui-col-sm-6 mui-col-xs-6">
					        	<div class="info-detail">							        		
					        		<div class="orange-point"></div>
					        		<p class="info-key">结束时间:</p>	
					        		<div class="info-value">12:33:20</div>
					        	</div>
					        </div>
					    </div>
					    
					    <div class="mui-row">
					        <div class="mui-col-sm-6 mui-col-xs-6">
					        	<div class="info-detail">							        		
					        		<div class="red-point"></div>
					        		<p class="info-key">任务状态:</p>	
					        		<div class="info-value">预约中</div>
					        	</div>
					        </div>
					    </div>
						
					</div>
					<div class="mui-card-footer card-footer">
						<button class="start mui-btn mui-btn-success mui-btn-outlined" >行程开始</button>
						<button class="finish mui-btn mui-btn-outlined" disabled = "true">行程结束</button>
					</div>
				</div>-->
			</div>
		</div>
		<script src="../js/mui.min.js"></script>
		<script src="../js/config.js"></script>
		<script src="../js/app.js"></script>
		<script>
			(function($) {
				mui.init({
					swipeBack: false,
					keyEventBind: {
						backbutton: false //关闭back按键监听
					},
					pullRefresh: {
						container: '#pullrefresh',
						up: {
							contentrefresh: '正在加载...',
							callback: pullupRefresh
						},
						down : {
	//						height:100,//可选,默认50.触发下拉刷新拖动距离,
							auto: true,//可选,默认false.首次加载自动下拉刷新一次
	//						contentdown : "下拉可以刷新",//可选，在下拉可刷新状态时，下拉刷新控件上显示的标题内容
	//						contentover : "释放立即刷新",//可选，在释放可刷新状态时，下拉刷新控件上显示的标题内容
	//						contentrefresh : "正在刷新...",//可选，正在刷新状态时，下拉刷新控件上显示的标题内容
							callback :pulldownRefresh //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
						}
					}
				});
				
				function formatHours(date){
					var hour = date.getHours();
					if(hour.toString().length == 1){
						hour = "0" + hour;
					}
					var minute = date.getMinutes();
					if(minute.toString().length == 1){
						minute = "0" + minute;
					}
					var second = date.getSeconds();
					if(second.toString().length == 1){
						second = "0" + second;
					}
					
					return hour + ":" + minute+ ":" + second;
				}
				
				function formatDate(date){
					var year = date.getYear();
					var month = date.getMonth()+1;
					var day = date.getDate();
					
					var hour = date.getHours();
					if(hour.toString().length == 1){
						hour = "0" + hour;
					}
					var minute = date.getMinutes();
					if(minute.toString().length == 1){
						minute = "0" + minute;
					}
					var second = date.getSeconds();
					if(second.toString().length == 1){
						second = "0" + second;
					}
					
					return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
				}
				
				function stateCheck(state){
					var result = "已结束";
					switch(state){
						case 0:
							result = "预约中";
							break;
						case 1:
							result = "在途中";
							break;
						case 2:
							result = "已结束";
							break;
					}
					
					return result;
				}
				
			
				function taskItem (task){		        
					var startTime = formatHours(new Date(task.startTimestamp*1000));
					var endTime = formatHours(new Date(task.endTimestamp*1000));
					var createdAt = formatDate(new Date(task.updatedAt));
					var startLonLat = task.startLon + "|" + task.startLat;
					var endLonLat = task.endLon + "|" + task.endLat;
					
					
					var innerHtml = '<div class="mui-card">'
									+	'<div class="mui-card-header mui-card-media">'
									+		'<img src="../images/car.png"/>'
									+		'<div class="mui-media-body">'
									+			task.purpose
									+			'<p>派单时间：'+createdAt+'</p>'
									+		'</div>'
									+	'</div>'
									+	'<div class="mui-card-content" >'
									+		'<div class="mui-row">'
									+	        '<div class="mui-col-sm-6 mui-col-xs-6">'
									+	        	'<div class="info-detail">'					        		
									+	        		'<div class="red-point"></div>'
									+	        		'<p class="info-key">联系人:</p>	'
									+	        		'<div class="info-value">'+task.linkman+'</div>'
									+	        	'</div>'
									+	        '</div>'
									+	        '<div class="mui-col-sm-6 mui-col-xs-6">'
									+	        	'<div class="info-detail">'						        		
									+	        		'<div class="orange-point"></div>'
									+	        		'<p class="info-key">电话:</p>'	
									+	        		'<div class="phone-value" id="phone-'+task.id+'">'+task.phone+'</div>'
									+	        	'</div>'
									+	        '</div>'
									+	    '</div>'
										    
									+	    '<div class="mui-row">'
									+	        '<div class="mui-col-sm-6 mui-col-xs-6">'
									+	        	'<div class="info-detail">'						        		
									+	        		'<div class="yellow-point"></div>'
									+	        		'<p class="info-key">始发地:</p>	'
									+	        		'<div class="info-value">'+task.startAddress+'</div>'
									+					'<p class="div-hide" id="startLonLat-'+task.id+'">'+startLonLat+'</button>'
									+	        	'</div>'
									+	        '</div>'
									+	        '<div class="mui-col-sm-6 mui-col-xs-6">'
									+	        	'<div class="info-detail">'					        		
									+	        		'<div class="green-point"></div>'
									+	        		'<p class="info-key">目的地:</p>	'
									+	        		'<div class="info-value" id="endAddress-'+task.id+'">'+task.endAddress+'</div>'
									+					'<p class="div-hide" id="endLonLat-'+task.id+'">'+endLonLat+'</button>'
									+	        	'</div>'
									+	        '</div>'
									+	    '</div>'
										    
									+	    '<div class="mui-row">'
									+	        '<div class="mui-col-sm-6 mui-col-xs-6">'
									+	        	'<div class="info-detail">'							        		
									+	        		'<div class="cyan-point"></div>'
									+	        		'<p class="info-key">开始时间:</p>'
									+	        		'<div class="info-value">'+startTime+'</div>'
									+	        	'</div>'
									+	        '</div>'
									+	        '<div class="mui-col-sm-6 mui-col-xs-6">'
									+	        	'<div class="info-detail">'						        		
									+	        		'<div class="orange-point"></div>'
									+	        		'<p class="info-key">结束时间:</p>'	
									+	        		'<div class="info-value">'+endTime+'</div>'
									+	        	'</div>'
									+	        '</div>'
									+	    '</div>'
										    
									+	    '<div class="mui-row">'
									+	        '<div class="mui-col-sm-6 mui-col-xs-6">'
									+	        	'<div class="info-detail">'							        		
									+	        		'<div class="red-point"></div>'
									+	        		'<p class="info-key">任务状态:</p>'	
									+	        		'<div class="info-value" id="state-'+task.id+'">'+stateCheck(task.state)+'</div>'
									+	        	'</div>'
									+	        '</div>'
									+	    '</div>'
											
									+	'</div>'
									+	'<div class="mui-card-footer card-footer">'
									+		'<button class="start mui-btn mui-btn-success mui-btn-outlined" id="start-'+task.id+'">行程开始</button>'
									+		'<button class="navigation div-hide mui-btn mui-btn-success mui-btn-outlined" id="navigation-'+task.id+'">地图导航</button>'
									+		'<button class="finish mui-btn mui-btn-outlined" id="finish-'+task.id+'" disabled = "true">行程结束</button>'
									+	'</div>'
									+'</div>';
					return innerHtml;
				};
				

				function taskDeal(taskJson, id){
					var taskUrl = config.getTaskUrl();
					
					mui.ajax(taskUrl,{
						data: taskJson,
						dataType: 'json',//服务器返回json格式数据
						type: 'post',//HTTP请求类型
						success: function(data){
							//服务器返回响应，根据响应结果，分析是否登录成功；
							//保存用户名、密码、token
							if(taskJson.state == 1){
								plus.nativeUI.toast("开始行程");
								
								//隐藏开始行程
								mui("#"+id)[0].style.display="none";
								var finishId = "finish-"+ id.split('-')[1];
								mui("#"+finishId)[0].disabled = false;
								
								var navigationId = "navigation-" + id.split('-')[1];
								mui('#'+navigationId)[0].style.display = "inline";
								
								var stateId = "state-"+ id.split('-')[1];
								mui('#'+stateId)[0].innerHTML = "行程开始中";
							} else if(taskJson.state == 2){
								plus.nativeUI.toast("行程结束");
//								element.style.display="none";
//								pulldownRefresh();
								mui("#"+id)[0].innerText = "行程结束";
								mui("#"+id)[0].disabled = true;
								var stateId = "state-"+ id.split('-')[1];
								mui('#'+stateId)[0].innerHTML = "行程结束";
								
								var navigationId = "navigation-" + id.split('-')[1];
								mui('#'+navigationId)[0].style.display = "none";
								
								pulldownRefresh();
							}
							
						},
						error: function(xhr,type,errorThrown){
							//console.log(xhr.response)
							var response = xhr.response;
							//errorResponse(JSON.parse(response));
							console.log(response)
						}
					});
				}
				
				//判断当前派单的状态
				function initView(task){
					if(task.state == 1){
						mui('#start-'+task.id)[0].style.display = "none";
						mui('#navigation-'+task.id)[0].style.display = "inline";
						mui('#finish-'+task.id)[0].disabled = false;
					}
				}

				var count = 1;
				/**
				 * 上拉加载具体业务实现
				 */
				function pullupRefresh() {
					console.log("上拉刷新");
					//获取当天任务
				    var listUrl = config.getRecentListUrl();
				    var token = app.getState().token;
				    count++;
				   	var todayList = {
				   		"date": 1,
				   		"limit": 10,
				   		"page": count,
				   		"token": token
				   	}
				   
				    mui.ajax(listUrl,{
						data: todayList,
						dataType: 'json',//服务器返回json格式数据
						type: 'get',//HTTP请求类型
						success: function(data){
							//服务器返回响应，根据响应结果，分析是否登录成功；
							//保存用户名、密码、token
							if(data.rows.length){
								var scroll = document.body.querySelector('.mui-scroll');
				                var tasks = data.rows;	
				                var len = tasks.length;
				                
				                if(len){
				                	for(var i = 0; i < len; i++) {
										var div = document.createElement('div');
										div.innerHTML = taskItem(tasks[i]);
										scroll.appendChild(div);
										
										initView(tasks[i]);
									}
					                
					                var startBtn = document.body.querySelector('.start');
									startBtn.addEventListener('tap', function(){
										
										var startId = this.getAttribute('id');
										var id = startId.split('-')[1];
										
										console.log(startId)
										
										var taskJson = {
											"id": id,
											"state": 1,
											"token": app.getState().token
										}
			            				taskDeal(taskJson, startId);
									})
									
									var finishBtn = document.body.querySelector('.finish');
									finishBtn.addEventListener('tap', function(){
										var finishId = this.getAttribute('id');
										var id = finishId.split('-')[1];
										
										var taskJson = {
											"id": id,
											"state": 2,
											"token": app.getState().token
										}
			            				taskDeal(taskJson, finishId);
									})
				                }
							}else{
								setTimeout(function() {
									mui('#pullrefresh').pullRefresh().endPullupToRefresh(true);
								}, 1000)
							}
							
			                
						},
						error: function(xhr,type,errorThrown){
							//console.log(xhr.response)
							var response = xhr.response;
							//errorResponse(JSON.parse(response));
							console.log(response)
						}
					});		
				}
				
				function pulldownRefresh() {
					console.log("下拉刷新");
					//获取当天任务
				    var listUrl = config.getRecentListUrl();
				    var token = app.getState().token;
				   	var todayList = {
				   		"date": 1,
				   		"limit": 10,
				   		"page": 1,
				   		"token": token
				   	}
				   
				    mui.ajax(listUrl,{
						data: todayList,
						dataType: 'json',//服务器返回json格式数据
						type: 'get',//HTTP请求类型
						success: function(data){
							//服务器返回响应，根据响应结果，分析是否登录成功；
							//保存用户名、密码、token
			                var tasks = data.rows;
			                var len = tasks.length;
			                
			                var scroll = document.body.querySelector('.mui-scroll');
			                scroll.innerHTML = "";
			                	
			                if(len){
			                	for(var i = 0, len = tasks.length; i < len; i++) {
									var div = document.createElement('div');
									div.innerHTML = taskItem(tasks[i]);
									scroll.appendChild(div);
									
									initView(tasks[i]);
								}
				                
				                var phoneBtn = document.body.querySelector('.phone-value');
								phoneBtn.addEventListener('tap', function(){
									var phoneId = this.getAttribute('id');
									var btnArray=['拨打','取消'];
									var phone = mui('#'+phoneId)[0].innerHTML;
									mui.confirm('是否拨打'+phone+'?','提示',btnArray,function(e){
						                if(e.index == 0){
						                    plus.device.dial(phone,false);
						                }
						            });
								})
								
								var navigatonBtn = document.body.querySelector('.navigation');
								navigatonBtn.addEventListener('tap', function(){
									var navigatonId = this.getAttribute('id');
									var id = navigatonId.split('-')[1];
									console.log("第三方")
									// 设置目标位置坐标点和其实位置坐标点
									var startLonLatId = "startLonLat-" + id;
									var startLonLat = mui('#'+startLonLatId)[0].innerHTML;
									var startLon = startLonLat.split('|')[0];
									var startLat = startLonLat.split('|')[1];
									
									var endLonLatId = "endLonLat-" + id;
									var endLonLat = mui('#'+endLonLatId)[0].innerHTML;
									var endLon = endLonLat.split('|')[0];
									var endLat = endLonLat.split('|')[1];
									
									var endAddressId = "endAddress-" + id;
									var endAddress = mui('#'+endAddressId)[0].innerHTML;
									
									var src = new plus.maps.Point(startLon, startLat); //起点 
									var dst = new plus.maps.Point(endLon, endLat); // 终点
									// 调用系统地图显示 
									plus.maps.openSysMap( dst, endAddress, src );
								})
								
				                var startBtn = document.body.querySelector('.start');
								startBtn.addEventListener('tap', function(){
									var startId = this.getAttribute('id');
									var id = startId.split('-')[1];
									
									var taskJson = {
										"id": id,
										"state": 1,
										"token": app.getState().token
									}
		            				taskDeal(taskJson, startId);
								})
								
								var finishBtn = document.body.querySelector('.finish');
								finishBtn.addEventListener('tap', function(){
									var finishId = this.getAttribute('id');
									var id = finishId.split('-')[1];
									
									var taskJson = {
										"id": id,
										"state": 2,
										"token": app.getState().token
									}
		            				taskDeal(taskJson, finishId);
								})
				                
				                count = 1;
				                setTimeout(function() {
									mui('#pullrefresh').pullRefresh().endPullupToRefresh(false);
								}, 1000)
			                } else {
			                	var noTask = '<div class="no-task">'
			                				+ '<p class="no-task-p">当日未有派单任务。</p>'
											+ '</div>';
				
								scroll.innerHTML = noTask;
			                }
						},
						error: function(xhr,type,errorThrown){
							//console.log(xhr.response)
							var response = xhr.response;
							//errorResponse(JSON.parse(response));
							console.log(response)
						}
					});		
					setTimeout(function() {
						mui('#pullrefresh').pullRefresh().endPulldownToRefresh();
					}, 1000)	
				}
				
				//添加newId自定义事件监听
				window.addEventListener('today',function(event){
				  	//获得事件参数
				  	//plus.nativeUI.toast(event.detail);
				  	pulldownRefresh();
				});
			})(mui);
		</script>
	</body>
</html>